import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class GamePanel extends JPanel {
    private static final int SIZE = 4;
    private final int[][] grid = new int[SIZE][SIZE];
    private final Random random = new Random();
    GamePanel(){
        setGridValue();
        setGridValue();
    }

    private void drawGrid(Graphics g,int value, int x, int y) {
        int p = (int)((int)Math.log(value)/Math.log(2));
        g.setColor(value == 0 ? Color.lightGray:new Color(250-p*20,240,200));
        g.fillRect(x, y, 100, 100);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, 100, 100);

        g.drawString(String.valueOf(value), x+50, y+50);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.lightGray);
        g.fillRect(0, 0, getWidth(), getHeight());
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                drawGrid(g, grid[i][j],j * 100, i * 100);
            }
        }
    }

    private void setGridValue() {
        int cnt = 0;
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (grid[i][j] != 0) {
                    cnt++;
                }
            }
        }
        if (cnt == SIZE * SIZE) {
            return;
        }
        int x, y;
        do {
            x = random.nextInt(SIZE);
            y = random.nextInt(SIZE);
        } while (grid[x][y] != 0);
        grid[x][y] = random.nextInt(10) < 5 ? 2 : 4;

    }
}
